package persistencia;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import dominio.Editor;;

public class EditorDAO{
	
	public static Editor newEditor(String nif) throws Exception {
		Editor result= null;
		String SQL="Select * from Persona where dni=?";
		Conexion bd=null;
		Exception ex=null;
		PreparedStatement p=null;
		try {
				bd = Broker.get().getBD();
				p = bd.prepareStatement(SQL);
				p.setString(1, nif);
				ResultSet r = p.executeQuery();
				if (r.next()) {
					result = new Editor(r.getString(1), r.getString(2), r.getString(3), r.getString(4), r.getString(5));
				} else {
					throw new Exception("La persona con NIF " + nif + " no existe");
				}			
		} catch (Exception e) {
			ex = e;
	}
		finally {
			bd.close();
			if (ex!=null)
				throw ex;
		}
		return result;
	}
	
// Modificar InvitacionDAO, AutorDAO y EditorDAO para contemplar que los id con autonumericos
	public static void insert(Editor editor) throws Exception{
		PersonaDAO.insert(editor);
		String SQL="Insert into Editor (dni) values (?)";
		Conexion bd=null;
		Exception ex=null;
		PreparedStatement p=null;
		try {
			bd=Broker.get().getBD();
			p=bd.prepareStatement(SQL);
			p.setString(1, editor.getDni());
			p.executeUpdate();
		}
		catch (Exception e) {
			ex=e;
		}
		finally {
			bd.close();
			if (ex!=null)
				throw ex;
		}
	}
	
	public static int consultaNum_pclaves(String dni) throws Exception{
		int nuevo = 0;
		String SQL = "SELECT COUNT(*) AS H FROM PalabraRevisor r, Where r.DNI= '"+dni+"'";
		Conexion bd = null;
		Exception ex = null;
		PreparedStatement p = null;
		try{
			bd = Broker.get().getBD();
			p = bd.prepareStatement(SQL);
			p.setString(1, dni);
			ResultSet r = p.executeQuery();
			if (r.next()) {
				nuevo=r.getInt("H");
			} else {
				throw new Exception("El autor con DNI " + dni + " no existe");
			}
		}catch (Exception e) {
			ex = e;
		} finally {
			bd.close();
			if (ex != null)
				throw ex;
		}
		return nuevo;
    }
	
	public static void delete(Editor editor) throws Exception {
		PersonaDAO.delete(editor);
	}
}
